#!/usr/bin/python
# -*- coding: utf-8 -*-
# author: yoshiii.yoshiii@googlemail.com
# you found this code on http://yoshiii-box.googlecode.com/svn/ 
#
import socket, time

port	    = 1024
sleep_time  = 2 

hostname   = "localhost"
verbose     = False
debug	    = False

def client(host, port, sleep_time):
    import os
    if debug: print "be client(%s, %i, %i)"%(host, port, sleep_time)
    snd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    try:
	    while True:
	#	data = os.popen("uptime").read()
#		data = "online: " + os.popen("users").read()[:-1]
		data = "online: " + os.popen("users").read().strip()
		if verbose: 
			print time.ctime(), 
			print 'sending to', 
			print (socket.gethostbyname(host), port), repr(data)
		snd_sock.sendto(data, (host, port))
		time.sleep(sleep_time)
    except KeyboardInterrupt:
	if verbose: print "Exiting, caught Keyboard Interrupt"

def server(host, port):
    if debug: print "be server(%s, %i)"%(host, port)
    rcv_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    rcv_sock.bind( (host, port) )
    if debug: print "bound to", (host, port)

    try:
	    while True:
		data, addr = rcv_sock.recvfrom(4096)
		if verbose: print time.ctime(), "received from", addr, repr(data)
    except KeyboardInterrupt:
	if verbose: print "Exiting, caught Keyboard Interrupt"

def main():
    import sys, getopt
    global hostname, port, sleep_time, verbose, debug
    optlist, args = getopt.getopt(sys.argv[1:], "csh:p:i:dv", ["client", "server", "host=", "port=", "intervall=", "debug", "verbose"])

    for o,a in optlist:
	if o in ["--client", "-c"]:
            beServer = False
    	elif o in ["--server", "-s"]:
            beServer = True
    	elif o in ["--host", "-h"]:
	    hostname = a
    	elif o in ["--port", "-p"]:
	    port = int(a)
    	elif o in ["--intervall", "-i"]:
	    sleep_time = int(a)
        elif o in ["--debug", "-d"]:
	    debug = True
        elif o in ["--verbose", "-v"]:
	    verbose = True
	else:
	    print "unknown option"
	    print "args: --client|--server"

    if debug: print optlist, args
#    if debug: print locals()
#    if debug: print globals()

    if beServer:
	server(hostname, port)
    else: 
	client(hostname, port, sleep_time)

if __name__ == '__main__':
    main()
